package com.cn.xiaonuo.sys.modular.file.util;

import com.cn.xiaonuo.sys.modular.images.Images;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 爬虫工具类
 * @author zhangyu
 */
public class JsoupUtil {

    //设置代理，模范浏览器
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";


    /**
     * 解析html中的轮播图
     *
     * @param html
     * @return
     */
    public static List<Images> getImagesByHtml(String html) {
        Document parse = Jsoup.parse(html);
        Elements select = parse.select("div.swiper-wrapper");// div中class为masthead
        Elements select1 = select.get(1).select("div.swiper-slide");
        List<Images> list=new ArrayList<>();
        for (Element element : select1) {
            System.out.println(element.getElementsByTag("a").attr("href"));
            System.out.println(element.getElementsByTag("img").attr("alt"));
//            图片加前缀 http://www.nncc626.com/titlepic/112738/1127380679_1619487241463_title0h.jpg
            String imgurl = element.getElementsByTag("img").attr("src");
            Images images = new Images();
            images.setImageurl(QiniuUtil.imageChangeBase64("http://www.nncc626.com/"+imgurl));
            images.setType(Images.type.INDEX);
            images.setName(element.getElementsByTag("img").attr("alt"));
            images.setCreateTime(new Date());
            images.setUsername("爬虫工具自动更新");
            list.add(images);
        }
        return list;
    }




    public static String sendGet(String url) {
        //1.生成httpclient，相当于该打开一个浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        CloseableHttpResponse response = null;
        String html = null;
        //2.创建get请求，相当于在浏览器地址栏输入 网址
        HttpGet request = new HttpGet(url);
        try {
            request.setHeader("User-Agent", USER_AGENT);
            request.setConfig(requestConfig);
            //3.执行get请求，相当于在输入地址栏后敲回车键
            response = httpClient.execute(request);
            //4.判断响应状态为200，进行处理
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //5.获取响应内容
                HttpEntity httpEntity = response.getEntity();
                html = EntityUtils.toString(httpEntity, "UTF-8");
            } else {
                //如果返回状态不是200，比如404（页面不存在）等，根据情况做处理，这里略
                System.out.println("返回状态不是200");
                System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6.关闭
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
        return html;
    }



    /**
     *     将网络地址对应的图片转换为base64
     * @param imagePath 网络图片路径
     * @return res 图片对应的Base64编码
     */
    public static String imageChangeBase64(String imagePath){
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(imagePath);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if(conn.getResponseCode() != 200) {
                return null;//连接失败/链接失效/图片不存在
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
        String s = new String(encode);
        return "data:image/jpeg;base64,"+s;
    }

}
